const path = require('path')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin= require('mini-css-extract-plugin')

function loadUse (loader) {
  const arr = [
    { loader: MiniCssExtractPlugin.loader },
    { loader: 'css-loader' },
    { loader: 'postcss-loader', options: { // 配置自动补全css
      postcssOptions: {
        plugins: [
          [
            'autoprefixer',
            {
              overrideBrowserslist: ['last 100 versions']
            }
          ],
          [
            'postcss-preset-env',
            {
              // Options
            }
          ]
        ]
      }
    } },
    { loader: loader }
  ]
  if (!loader) {
    arr.pop() // 如果不传递loader,删除最后一项
  }
  return arr
}
module.exports = {
  mode: 'development',
  entry: {
    app: './src/index.js'
  },
  output: {
    path: path.resolve(__dirname, '../', 'build'),
    filename: '[name].[hash:8].js'
  },
  plugins: [
    new CleanWebpackPlugin({
      verbose: true
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: './src/assets',
          to: 'static'
        },
        {
          from: './public/favicon.ico',
          to: ''
        }
      ]
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[name].[hash:8].css'
    }),
    new HtmlWebpackPlugin({
      template: './public/index.html',
      title: 'webpack 神奇之旅'
    })
  ],
  module: { 
    rules: [
      {
        test: /\.css$/, 
        use: loadUse()
      },
      {
        test: /\.scss$/, 
        use: loadUse('sass-loader')
      },
      {
        test: /\.less$/, 
        use: loadUse('less-loader')
      },
      {
        test: /\.stylus$/, 
        use: loadUse('stylus-loader')
      },
      // css中有本地背景图片地址
      {
        test: /\.(jpg|jpeg|png|gif|webp|svg)$/,
        use: {
          loader: 'url-loader',
          options: {
            // 如果设置的值足够大，显示base64图片地址（内存中）
            // 如果设置的值足够小，显示图片的地址
            limit: 2048000, // 单位为字节
            publicPath: './../' // css 采取模块化，
          }
        }
      }
    ]
  }
}